package com.icehand.json.benchmark;

import com.icehand.echarts.model.EchartsOption;
import com.icehand.json.model.FullName;
import com.icehand.json.model.User;
import com.icehand.json.utils.*;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author zhoujunmei
 * @date 2019-08-02 10:44
 * @remark
 */
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class JsonSerializeBenchmark {
    @Param({"1000","10000"})
    private int count;

    private User user;

    public static void main(String[] args) throws Exception {
        Options options = new OptionsBuilder()
                .include(JsonSerializeBenchmark.class.getSimpleName())
                .forks(1)
                .warmupIterations(0)
                .build();

        Collection<RunResult> results = new Runner(options).run();
        EchartsOption echartsOption = ResultExporter.exportEchartsResult("JSON序列化性能", results, "count", "秒");
        System.out.println(OkHttpUtil.post("http://localhost:8888",echartsOption));
    }

    @Benchmark
    public void gson(){
        for (int i =0; i<count; i++) {
            GsonUtil.toJSONString(user);
        }
    }

    @Benchmark
    public void fastjson(){
        for (int i =0; i<count; i++) {
            FastjsonUtil.toJSONString(user);
        }
    }

    @Benchmark
    public void jsonLib(){
        for (int i =0; i<count; i++) {
            JsonLibUtil.toJSONString(user);
        }
    }

    @Benchmark
    public void jackson(){
        for (int i = 0; i < count ; i++){
            JacksonUtil.toJSONString(user);
        }
    }

    @Setup
    public void prepare(){
       //初始化user
        List<User> friends = new ArrayList<>();
        Map<String,String> role = new HashMap<>();
        role.put("salve","1");
        role.put("sc","ssd");
        friends.add(new User().setFullName(new FullName().setFirstName("蔡徐坤")).setAge(22222).setBirthday(new Date())
                .setId(1111L).setTags(Arrays.asList("唱","跳","rap","篮球")).setRoles(role));
        friends.add(new User().setFullName(new FullName().setFirstName("xxx")).setAge(222).setBirthday(new Date())
                .setId(2222L).setTags(Arrays.asList("hahah","sddsd")).setRoles(role));
        user = new User().setFullName(new FullName().setFirstName("蔡徐坤")).setAge(22222).setBirthday(new Date())
                .setId(1111L).setTags(Arrays.asList("唱","跳","rap","篮球")).setRoles(role).setFriends(friends);
    }

    @TearDown
    public void shutdown(){

    }
}
